var SwordSelect = new Class({
    Implements : [Events, Options],
    name:'SwordSelect',
    $family:{name:'SwordSelect'},
    options : {
        name : null,//组件name
        type : null,//组件类别，默认是单选框
        prikey : null,//下拉框prikey,相当于code
        lines :10,//显示的最大行数
        height:21,//显示行的高度
        data : null,//数据
        pNode : null,//父节点
        edit:'true',//是否可编辑
        disable:null,//是否可以编辑和可以弹出框
        rule : null,//校验规则
        msg:null,//校验提示信息
        parent:null,//如果是级联下拉,值为父选项的name
        child: null,//如果是级联下拉,值为子选项的name
        dataname:null,//指定数据集名称，如果不指定该名称,以name代替
        cachename:null,//指定缓存代码表的名称
        submitFormat:null,//需要提交的内容，默认是提交代码，可以为任意组合"{code}|{mc}"或者 "{mc}"或者"{dm}"
        onChange : $empty,//当选择框发生改变时的回调函数(el:选中的行对象，String:code值)
        onSelect : $empty,//选择时的回调函数 (string:code)
        onShow   : $empty,//下拉列表显示时的回调函数
        onHide   : $empty//下拉列表隐藏时的回调函数
        ,dataFilter:null//自定义的下拉列表的数据过滤，适用的场景是要根据业务上的字段进行过滤
        ,onSubmitBefore   : $empty//点击才装载数据之前触发
        ,popWidth : null//弹出层的宽度
        ,displayCode:'false'//是否同时显示code和caption
        ,popFormat:null//弹出层的显示格式定义，与submitFormat的定义相似
        ,inputFormat:null//输入框的显示格式定义，与submitFormat的定义相似
        ,handInput:'false'//是否支持自定义手动输入
        ,addCaption:''//是否增加"全部“的选项
        ,addCode:''//定义全部选项的code值
        ,x:null
        ,showAbstract:"false"
        ,popmaxw:400
    },
    box            : null, //选项的Input
    selectbox      : null, //选项框div层对象
    selectedIndex  : null, //当前选中文本的索引
    currentElement : null, //当前选中文本的HTMLElement
    currentText    : null, //当前选中的文本
    validate       : null, //校验对象
    dataObjHash:new Hash(),
    dataArrayHash:new Hash(),
    selFx : null,
    rebuild:null,
    hasBoxDiv:false,
    CacheData:null,//数据缓存,管理懒加载过来的数据
    updateCache:function(name, data) {
        if(this.CacheData == null) {
            this.CacheData = new Hash();
            this.CacheData.set(name, data);
        } else {
            var cache = this.CacheData.get(name);
            if($defined(cache)) {
                cache.combine(data);
            } else {
                this.CacheData.set(name, data);
            }
        }
    },
    getDataInCache:function(tid, name, pcode) {
        var reqServer = false,data;
        if($defined(this.box.get("parent"))) {
            if(!$defined(pcode) || !$chk(pcode)) {
                this.build_options([]);
                return;
            }
        }
        if(this.CacheData != null && $defined(this.CacheData.get(name))) {
            data = this.dataFilter(this.CacheData.get(name));
            if(data.length == 0)reqServer = true;
        } else {
            reqServer = true;
        }
        if(reqServer) {
            var sb = null;
            this.options.onSubmitBefore = this.box.get("onSubmitBefore");
            if($defined(this.options.onSubmitBefore) && $chk(this.options.onSubmitBefore)) {
                sb = this.getFunc(this.options.onSubmitBefore)[0]();
            }
            var vName = this.box.get("name");
            if($type(sb) == 'SwordSubmit') {//onSubmitBefore 返回了提交组件
            	this.selectLoading();
                if(this.box.get('initOnSubmitBefore') != 'true') {
                    sb.addEvent('onSuccess', function(req, res) {
                        this.unselectLoding();
                        var data;
                        res.data.each(function(item, index) {
                            if((item.name || item.dataName) == vName) {
                                data = item.data;
                                return;
                            }
                        });
                        this.updateCache(name, data);
                        if(this.box.get("name") == vName) {
                            this.build_options(data);
                            xyposition(this.box, this.box_div);
                        }
                    }.bind(this));
                    sb.addEvent('onError', function() {
                        alert("使用onSubmitBefore返回的提交组件：从后台返回数据出错了。");
                    });
                    this.box.set('initOnSubmitBefore', 'true');
                }
                sb.options.mask = 'false';
                sb.submit();
            } else if($chk(tid)){
            	this.selectLoading();
                var req = pc.getReq({'tid':tid,'widgets':[
                    {
                        'sword':"SwordForm",
                        'name' :name,
                        'data' :{'pcode':{value:pcode}}
                    }
                ]});
                pc.postReq({
                    req:req,
                    loaddata:"widget",
                    onSuccess:function(res) {
                        this.unselectLoding();
                        var sd = $defined(res.data[0]) ? res.data[0].data : null;
                        this.updateCache(name, sd);
                        if(this.box.get("name") == vName) {
                            this.build_options(sd);
                            xyposition(this.box, this.box_div);
                        }
                        this.def_select(this.box.get('code'));
                    }.bind(this),
                    onError:function() {
                        alert("从服务器端获取数据出错了,请求的tid为【" + tid + "】");
                    }.bind(this)
                });
            }else  this.unselectLoding();
        } else {
            this.build_options(data);
        }
    },
    selectLoading:function() {
        if(this.box_div.get("state") != "loading") {
            var li = new Element('div', {'class':'swordselect-list-item','name':'loading'}).inject(this.selectbox);
            var ld = new Element('div').inject(li);
            new Element("div", {'class':'selectLoding'}).inject(ld);
            new Element("div", {'class':'selectLoding_text'}).appendText(i18n.selectLoading).inject(ld);
        }
        this.box_div.set("state", "loading");
        this.selectbox.setStyle("height", "");
        this.box_div.setStyles({'display':'block',
            'left':this.box._getPosition().x,
            'top' :this.box._getPosition().y + this.box.getHeight()});
        //this.box_div.fade('in');
    },
    unselectLoding:function() {
        this.box_div.set("state", "");
        this.selectbox.getElements('div').each(function(li) {
            li.destroy();
        }.bind(this));
    },
    genarateInputContent:function(obj) {
        var content = this.box.get('inputFormat');
        if(!$defined(content))content = "{caption}";
        return this.genarateContent(obj, content);
    },
    genaratePopContent:function(obj) {
        var content = this.box.get('popFormat');
        if(!$defined(content))content = "{caption}";
        return this.genarateContent(obj, content);
    },
    genarateContent:function(obj, content) {
        if(!$defined(content)) {
            content = "{code}";
        }
        if($type(obj) == "element"&&$chk(obj.get("code"))) {
        	content = obj.get('submitFormat')||content;
        	obj = {'code':obj.get("code"),"caption":obj.get("caption")||obj.get("value")};
        }
        return content.substitute(obj);
    },
    initialize: function(options) {
       /* if(pc.SwordSelectWindowClick) return;
        pc.SwordSelectWindowClick = true;*/
    	if(pc.select4grid&&pc.select)return;
        window.document.addEvent('click', function(e) {
            var obj = e.target;
            while(obj.parentNode && obj != this.box && obj != this.selDiv) obj = obj.parentNode;
            if(obj != this.box && obj != this.selDiv && this.box) {
                if(this.box.get("display") == 'true') {
                    if($defined(this.box.onSelectBlur)) {
                        this.box.onSelectBlur(this.box.get('value'));
                    }
                }else if($chk( this.box_div) && this.box.get("id") != this.box_div.get("id")){
                	var curSelected = $(this.box_div.get("id"));
                	this.box_div.setStyles({'left':'-500px','top':'-500px'});
                    //this.box_div.fade('out');
                    this.box_div.set("state", "");
                    curSelected.set('display', 'false');
                    curSelected.getParent("td").getNext().getElement(".swordselect-selimg").removeClass('swordselect-selimg-over');
                }
                if(this.box.get('handInput') == "true" && !$chk(this.box.get('realvalue')) && $chk(this.box.get("value"))) {
                	this.box.set({'code':this.box.get("value"),'realvalue':this.box.get("value")});  
                }
                this.hide();
                if(!$(e.target).hasClass('sGrid_data_row_item_select')) {
                    this.execGridOnFinished();
                }
            }
        }.bind(this));
    },
    execGridOnFinished:function() {
        if($defined(this.grid_onFinished)) {
            this.grid_onFinished(this.box.get('value'), this.box.get('code'), this.box.get('realvalue'), this.box.retrieve("allDb"));
            this.grid_onFinished = null;
        }
    },
    setValidate:function(validate) {
        this.validate = validate;
    },
    initParam:function(node, parent) {
        if(parent && parent.name == 'SwordGrid') {
            this.grid = parent;
        } else {
            this.grid = null;
        }
        $extend(this.options, {
            name : null,//组件name
            type : null,//组件类别，默认是单选框
            prikey : null,//下拉框prikey,相当于code
            lines :10,//显示的最大行数
            width :null,//选择框的宽度
            height:21,//显示行的高度
            data : null,//数据
            pNode : null,//父节点
            rule : null,//校验规则
            parent:null,//父选项名字
            child: null,//子选项名字
            dataname:null,//指定数据集名称
            cachename:null,//客户端缓存
            pcode:null,//制定根节点的父亲节点的值是多少
            defValue:null,//默认选中值
            defIndex:null,//默认选中索引
            tid:null,
            onChange : $empty,//当选择框发生改变
            onSelect : $empty,//选择时
            onShow   : $empty,//下拉列表显示时
            onHide   : $empty,//下拉列表隐藏时
            dataFilter:null
            ,onSubmitBefore   : $empty,//点击才装载数据之前触发
            disable:null,
            submitFormat:null
            ,popWidth : null //弹出层的宽度
            ,displayCode:'false'//是否同时显示code和caption
            ,inputFormat:null
            ,popFormat:null
            ,edit:'true'
            ,handInput:'false'
            ,addCaption:''
            ,addCode:''
        });
        this.htmlOptions(node);
        if(parent && parent.name != "SwordGrid")node.set({'onChange':'','onchange':''});
        var space = this.options.pNode.retrieve("space");
        if($defined(this.options.parent)) {
            var pSel = space.getElements("*[name='" + this.options.parent + "']")[0];
            pSel.set('child', this.options.name);
            if(!$chk(this.options.dataname)) {
                var root = this.getRoot();
                this.options.dataname = ($chk(root.get("dataname"))) ? root.get("dataname") : root.get("name");
            }
        }
        var chds = space.getElements("*[parent]");
        for(var i = 0; i < chds.length; i++) {
            var name = chds[i].get("parent");
            var oj = space.getElement("*[name='" + name + "']");
            if($defined(oj))oj.set("child", chds[i].get("name"));
        }
        this.options.data = node.getChildren(">div");
        this.build_selectbox(parent);
        if(this.box.get("mode") != 2) {
            this.box.addEvent('click', function(e) {
                if(parent && parent.name == 'SwordGrid') {
                    this.grid = parent;
                } else {
                    this.grid = null;
                }
                if($defined(e)) {
                    if(this.box == $(new Event(e).target)) {
                        this.rebuild = false;
                    } else {
                        if(this.box.get("display") == 'true') {
                            this.hide();
                            if(!$(e.target).hasClass('sGrid_data_row_item_select')) {
                                this.execGridOnFinished();
                            }
                            this.box.set('display', 'false');
                        }
                        this.box = $(new Event(e).target);
                        this.selDiv = this.getImgEl(this.box);
                        this.box.removeClass("swordform_item_input_bg");
                        this.rebuild = true;
                    }
                }
                if(this.box.get('display') == 'true') {
                    //this.hide();
                } else {
                    this.show();
                    this.box.focus();
                }
            }.bind(this));
              this.box.addEvent('blur', function(e) {
              	if(this.box.get("value")==""){
                this.box.addClass("swordform_item_input_bg");
               }
          		}.bind(this));
            this.selDiv.addEvent('click', function(e) {
                if(parent && parent.name == 'SwordGrid') {
                    this.grid = parent;
                } else {
                    this.grid = null;
                }
                if(this.selDiv == $(new Event(e).target)) {
                    this.box = this.getBoxEl(this.selDiv);
                    this.rebuild = false;
                } else {
                    if(this.box.get("display") == 'true') {
                        this.hide();
                        if(!$(e.target).hasClass('sGrid_data_row_item_select')) {
                            this.execGridOnFinished();
                        }
                        this.box.set('display', 'false');
                    }
                    this.selDiv = $(new Event(e).target);
                    this.box = this.getBoxEl(this.selDiv);
                    this.rebuild = true;
                }
                this.box.removeClass("swordform_item_input_bg");
                if(this.box.get('display') == 'true') {
                    //this.hide();
                } else {
                    this.show();
                    this.box.focus();
                }
            }.bind(this));
        } else {
            this.box.addEvent("click", function(e) {
                if($defined(e)) {
                    if(this.box == $(new Event(e).target)) {
                        this.rebuild = false;
                    } else {
                        if(this.box.get("display") == 'true') {
                            this.hide();
                        }
                        this.box = $(new Event(e).target);
                        this.selDiv = this.getImgEl(this.box);
                        this.rebuild = true;
                    }
                }
                if(this.box.get('display') == 'true') {
                    this.hide();
                } else {
                    this.change_element_by_char();
                    this.box.focus();
                }
            }.bind(this));
            this.selDiv.addEvent("click", function(e) {
                if(this.selDiv == $(new Event(e).target)) {
                    this.rebuild = false;
                } else {
                    if(this.box.get("display") == 'true') {
                        this.hide();
                    }
                    this.selDiv = $(new Event(e).target);
                    this.box = this.getBoxEl(this.selDiv);
                    this.rebuild = true;
                }
                if(this.box.get('display') == 'true') {
                    this.hide();
                } else {
                    this.change_element_by_char();
                    this.box.focus();
                }
            }.bind(this));
        }
        if($defined(this.options.defValue) || $defined(this.options.defIndex)) {
            this.initData(this.options.defValue, this.box, this.options.defIndex);
        }
        this.box.addEvent("keyup", this.change_item_on_keyup.bind(this));
    },
    getBoxEl:function(imgdiv) {//根据下拉div找到input
        return imgdiv.getParent().getPrevious().getElement('.swordform_item_oprate');
    },
    getImgEl:function(inputEl) {//根据input找到下拉div
        return inputEl.getParent().getNext().getElement(".swordselect-selimg");
    },
    boxtd: null,imgtd: null,
    getRoot:function() {
        var parent = this.options.parent;
        var space = this.box.retrieve("space");
        while($defined(parent)) {
            var p = space.getElements("*[name='" + parent + "']")[0].get("parent");
            if($defined(p))parent = p; else break;
        }
        return space.getElements("*[name='" + parent + "']")[0];
    },
    isMulti:function(data) {
    	if(this.grid){
    		return this.gridMulti;
    	}else{
    		return (this.getChildEls(this.box.get("name")).length!=0) || $defined(this.box.get('parent'))||$defined(this.box.get("pcode"));
    	}
    },
    initData:function(d, box, idx) {
        this.box = $(box);
        this.selDiv = this.getImgEl(this.box);
        if(d == "") {
            if($defined(this.box.get("defValue")) || $defined(this.box.get("defIndex"))) {
                d = this.box.get("defValue");
                idx = this.box.get("defIndex");
            } else {
                this.box.set('value', "").set('realvalue', "").set("code", "").store("allDb", {'code':'','caption':''});
                return;
            }
        }
        if((!$defined(d) || !$chk(d)) && (!$defined(idx) || !$chk(idx)))return;
        if($type(d) == "string")d = d.toHash();
        if($type(d) == "object")d = new Hash(d);
        var rv;
        if($type(d) == "hash") {
            var obj = {};
            d.each(function(v, k) {
                obj[k] = v;
            }, this);
            rv = this.genarateContent(obj);
            this.box.set({'value':this.genarateInputContent(obj),'code':d.get('code'),'realvalue':rv});
            this.box.store("allDb", obj);
        } else {
            var data = this.getOptionsData();
            if(!$defined(data))return;
            if($defined(d) || $chk(d)) {
                data.each(function(node) {
                    if($type(node) == 'element') {
                        node = {caption:node.get('caption'),code:node.get('code')};
                    }
                    if(node.code == d) {
                        rv = this.genarateContent(node);
                        this.box.set({'value':this.genarateInputContent(node),'code':node.code,'realvalue':this.genarateContent(node)});
                        this.box.store("allDb", node);
                    }
                }, this);
            } else if($defined(idx) || $chk(idx)) {
                var node = data[idx / 1];
                if($defined(node)) {
                    if($type(node) == 'element') {
                        node = {caption:node.get('caption'),code:node.get('code')};
                    }
                    rv = this.genarateContent(node);
                    this.box.set({'value':this.genarateInputContent(node),'code':node.code,'realvalue':this.genarateContent(node)});
                    this.box.store("allDb", node);
                }
            }
        }
        return rv;
    },
    divTable:null,
    build_selectbox: function(parent) {
        /* var width = 144;
        var v_width = 180;
        var v_imgWidth = 17;
        if($defined(parent) && parent.name == 'SwordForm') {
            //width = parent.dftsize.FiledWidth.toInt() - 16;
            v_width = parent.dftsize.VFiledWidth;
            v_imgWidth = parent.dftsize.VimgWidth;
        }
        if($defined(this.options.width)) {
            width = this.options.width;
        } else if(parent.userSize && parent.userSize.FiledWidth) {
            width = parent.userSize.FiledWidth.toInt() - 17 + 'px';
        } else
            width = '128px'; */ //0511
        var mode = 0;
        //var div = new Element('div', {'class':'swordform_field_wrap'}).inject(this.options.pNode);
        this.divTable = Sword.utils.createTable(this,true,true);
        if(this.options.pNode.hasClass("swordform_field_wrap")) {
            mode = 1;
            this.divTable.setStyle('float', 'left');
        }
        this.box = new Element('input', {
            'type' : 'text',
            'rule' : this.options.rule,
            'msg':this.options.msg,
            'class'  : 'swordform_item_oprate swordform_item_input swordform_item_input_bg',
            'widget':'select',
            'name' : this.options.name,
            'submitFormat':this.options.submitFormat,
            'prikey':this.options.prikey,
            'child':this.options.child,
            'parent':this.options.parent,
            'lines':this.options.lines,
            'lineheight':this.options.height,
            'dataname':this.options.dataname,
            'cachename':this.options.cachename,
            'pcode':this.options.pcode,
            'tid':this.options.tid,
            'defValue':this.options.defValue,
            'value': '',
            'defIndex':this.options.defIndex,
            'dataFilter':this.options.dataFilter,
            'vType':this.validate.options.vType,
            'styles':{
//                'width':width, //0511
                'float':'left'
            },
            'popWidth':this.options.popWidth,
            'displayCode':this.options.displayCode,
            'inputFormat':this.options.inputFormat,
            'popFormat':this.options.popFormat,
            'handInput':this.options.handInput
            ,'addCaption':this.options.addCaption
                ,'addCode':this.options.addCode
        }).inject(this.boxtd);
        this.box.store('widgetObj', this);//向input存入对象
        if(this.options.edit == "false") {
            this.box.set('readonly', true);
        }
     
        if(this.options.disable == 'true') {
        	this.box.removeClass("swordform_item_input_bg");
            this.box.set('disabled', true);
            this.box.setStyle('cursor', "default");
        }
        if(this.options.type == "selectsolely") {
            this.box.set("mode", 2);
        }
        this.box.store('data', this.options.data).set('on_change', this.options.onChange).set('onSelect',
                this.options.onSelect).store('onShow', this.options.onShow).store('onHide', this.options.onHide)
                .store('onSubmitBefore', this.options.onSubmitBefore);
        this.selDiv = new Element('div', {'class':'swordselect-selimg',
            'styles':{'float':'left'},
            'vType':this.validate.options.vType,
            'events':{
                'mouseover':function(e) {
                    var Input = this.getBoxEl($(new Event(e).target));
                    if(Input.get('display') == 'false')
                        Event(e).target.addClass('swordselect-selimg-over');
                }.bind(this),
                'mouseout':function(e) {
                    var Input = this.getBoxEl($(new Event(e).target));
                    if(Input.get('display') == 'false')
                        Event(e).target.removeClass('swordselect-selimg-over');
                }.bind(this)
            }}).inject(this.imgtd);
        if((this.options.rule || "").indexOf("must") > -1 && parent.options.requiredSign == "field") {
            new Element("span", {'styles':{'color':'red','float':'left'},'html':"*"}).inject(this.divTable);
        }
        if(this.options.disable == 'true') {
            this.disable(this.box);
        }
        var wrapDiv;
        if(mode == 0) {
            if(parent.name == "SwordForm" && parent.isVal() && $defined(this.options.rule)) {
//                wrapDiv = new Element("div", {'class':'swordform_field_valiwrap','styles':{'visibility':'hidden'}})
//                        .inject(this.divTable.getChildren()[0].getChildren()[0]);
//                this.box.valWrapDiv=wrapDiv;
//                new Element('div', {'class':'swordform_fieldimg_nomal','styles':{'float':'left'}}).inject(wrapDiv);
//                new Element('div', {'name':'msgText','styles':{'margin-left':v_imgWidth,'text-align':'left'}}).inject(wrapDiv);
                wrapDiv = Sword.utils.createElAfter(this.divTable.getChildren()[0].getChildren()[0], this.box);

                //if(width != '100%')this.divTable.setStyle('width', width.contains('%') ? width : width.toInt() + v_width + 26);
            }
           /* if(width != '100%'){
                this.box.setStyle('width',width);
                this.divTable.setStyle('width','auto');
            }*/
         
	        	 if(!this.grid)Sword.utils.setWidth(this.options.x||this.options.width,parent?parent.userSize:null,this.divTable,this.box,true);//0511
           
//            else {
//                if(width != '100%')this.divTable.setStyle('width', width.contains('%') ? width : width.toInt() + 26);
//            }
        }
        if(!this.hasBoxDiv) {
            this.createBoxDiv();
            this.hasBoxDiv = true;
        }
        //计算输入框的宽度
        //this.box.setStyle('width', div.getWidth() - 18);

    },
    createBoxDiv:function() {
        this.box_div = new Element('div', {'class':'swordselect-list','id':this.box.get("id")}).inject(document.body);
        this.selectbox = new Element('div', {'class' : 'swordselect-list-inner'}).inject(this.box_div);
        this.sConsole = new Element('div', {'class' : 'swordselect-list-inner'}).setStyle('display', 'none').inject(this.box_div);
        new Element("div", {'class':'swordselect_csl_pre','events':{
            'click':this.getNextPageData.bind(this, [-1])
        }}).inject(this.sConsole);
        new Element("div", {'class':'swordselect_csl_next','events':{
            'click':this.getNextPageData.bind(this, [1])
        }}).inject(this.sConsole);
        //this.selFx = new Fx.Scroll(this.selectbox, {duration:10});
    },
    getValue:function(el) {
    	el=el||this.box;
    	if(el.get("submitFormat")) return this.genarateContent(el);
        return ($chk(el.get('code'))) ? el.get('code') : el.get('value');
    },
    getParentValue:function() {
        var pBox = this.getBoxParent().retrieve("space").getElements("*[name='" + this.box.get("parent") + "']")[0];
        return ($chk(pBox.get('code'))) ? pBox.get('code') : pBox.get('value');
    },
    getBoxParent: function() {
        return this.grid ? this.box.getParent('div.sGrid_data_row_item_div') : this.box.getParent();
    },
    getOptionsData:function(pcode,bz) {
    	var loadData = null;
        this.options.data = this.box.retrieve("data");
        if(!this.grid && !this.options.data ){//表单中取法
        	this.options.data = $(this.box.get("id")+"_tpl").getChildren(">");
        }
        if (this.options.data.length == 0) {
        	var d="";
        	var dataname = this.box.get("dataName");
            d =pc.getInitDataByDataName(dataname);
        	if(!$defined(d)){
                var cname = this.box.get("cacheName");
            	if($defined(cname)){
            		d =pc.getInitDataByDataName(cname,'cacheName');
            	}
                if (!$defined(d)) {
                    return;
                }
        	}
            loadData = this.options.data = d.data;
            this.options.dataname=dataname;
            if(loadData.length>30){
            	this.createTDHashAArray();
            }
        }
        if (!$defined(bz)) {
            loadData = this.dataFilter(this.options.data,pcode);
        }
        return loadData;
    }
    ,createTDHashAArray:function(){
    	var dataName=this.options.dataname;
    	if(!this.dataObjHash.get(dataName)){
    		var selectArray=this.options.data;
    		var selectDataHash=new Hash();
    		selectArray.each(function(item){
    			selectDataHash.set(item.code,item);
        	});
    		selectArray.each(function(item){
    			if(!$chk(item.ccm)){
        			this.setNodeDataCCM(selectDataHash,item,"",item);
        		}
        	}.bind(this));
    		this.dataObjHash.set(dataName,selectDataHash);
    		this.dataArrayHash.set(dataName,selectArray);
    	};
    }
    ,setNodeDataCCM:function(hashObj,item,ccm,yItem){
    	var pNode=hashObj.get(item.pcode);
    	if($chk(pNode)){
    		if(pNode.ccm!==undefined&&pNode.ccm!=""){
    			yItem.ccm=pNode.ccm+","+pNode.code;
    		}else{
    			ccm=pNode.code+","+ccm;
    	    	this.setNodeDataCCM(hashObj,pNode,ccm,yItem);
    		}
	    }else{yItem.ccm=ccm.substring(0,ccm.length-1);}
    }
    ,getPosterityForNodeData:function(node){
    	var nCccm=node.ccm;
    	var tempArray=this.dataArrayHash.get(this.options.dataname);
    	return  tempArray.filter(function(c){
			return c.ccm.indexOf(nCccm)!=-1;
    	});
    }
    ,getChildForNodeData:function(node){
    	return this.getPosterityForNodeData(node).filter(function(c){return c.pcode==node.code;});
    }
    ,dataFilter:function(loadData,pcode) {
        var topCode = this.box.get("pcode");
        var dataName=this.options.dataname;
        var dataHash=this.dataObjHash.get(dataName);
        if($defined(this.box.get("parent"))) {
            var pcode = pcode ? pcode : this.getParentValue();
            if($chk(pcode)) {
            	if(dataHash){
            		var pNode=dataHash.get(pcode);
        			loadData=this.getChildForNodeData(pNode);
        		}else{
	                loadData = loadData.filter(function(item) {
	                    return ($type(item) == 'element') ? (item.get('pcode') == pcode) : (item.pcode == pcode);
	                }, this);
        		}
            } else {
                loadData = [];
            }
        }else if(this.isMulti(loadData)) {
        	if(this.options.pNode && this.options.pNode.getHTML().contains("pcode")){//如果原标签上定义了pcode,再执行过滤,反之不过滤
	        	var b = $defined(topCode) ? [topCode] : ["null",'',"undefined",null,undefined];
	            loadData = loadData.filter(function(item) {
	                return ($type(item) == 'element') ? b.contains(item.get('pcode')) : b.contains(item.pcode);
	            }, this);
        	}else{
        		if(dataHash){
        			loadData=this.dataArrayHash.get(dataName).filter(function(item){return item.ccm=="";});
        		}
        		else{
	        		loadData=loadData.filter(function(item){//查找出一级节点.
	        			var tpcode=item.pcode;
	        			return loadData.filter(function(itemn){return itemn.code==tpcode;}).length==0?true:false;
	        		});
        		}
        	}
        } 
        return loadData;
    },
    build_options: function(loadData) {
    	var oHeight=this.options.height;
        var height = oHeight * 2;
        if($defined(loadData)) {
            if($chk(this.box.get('addCaption')))loadData = [
                {caption:this.box.get('addCaption'),code:this.box.get("addCode") || "all"}
            ].extend(loadData);
            var ldl=loadData.length;
            height = (ldl < this.box.get('lines')) ? oHeight * ldl : oHeight * this.box.get('lines');//this.options.lines;
            var tempFrac = document.createDocumentFragment();//yt修改guoyan,createDocumentFragment高效一些
            loadData.each(function(node, index) {
            	var itemClass = "swordselect-list-item";
                if($type(node) == 'element') {
            		node = {caption:node.get('caption'),code:node.get('code')};
                }
                if(this.box.get("showAbstract")=="true"){
                	itemClass = "swordselect-list-item swordselect-list-item-absStyles";
            		height = "";
                }
                var tempText=this.genaratePopContent(node);
                
                var li = new Element('div', {
                    'title':tempText,
                    'text':tempText,
                    'value':node.code,
                    'caption':node.caption,
                    'index':index,
                    'class':itemClass,
                    'events':{
                        'mouseover':function() {
                        	li.addClass('swordselect-selected');
                        },
                        'mouseout':function() {
                        	li.removeClass('swordselect-selected');
                        }
                    }
                });//.inject(this.selectbox);
            	if(this.box.get("showAbstract")=="true"){
	                var absDiv = new Element('div', {
	                	 'text':node.abs,
	                     'class':'swordselect-list-item-abs'
	                 }).inject(li);
                }
                li.store("allDb", node);
                li.addEvent('click', function(e) {
                    this.change_item(li);
                    this.box.removeClass("swordform_item_input_bg");
                    if(this.box.get("mode") == 2) {
                        this.getNextPageData();
                    } else {
                        this.hide();
                    }
                    this.execGridOnFinished();

                }.bind(this));
                tempFrac.appendChild(li);
            }.bind(this));
            this.selectbox.appendChild(tempFrac);
            this.calculateConsole();
            //用户设置弹出层的宽度
            this.options.popWidth = this.box.get("popWidth");
            var minw =  $chk(this.options.popWidth) ? this.options.popWidth : this.box.getWidth()+14;
//            var maxw =  this.options.popmaxw;//$chk(this.options.popWidth) ? this.options.popWidth*1.2 : this.box.getWidth()*1.2;
            if(Browser.Engine.trident4){
            	this.selectbox.setStyles({
                    'width'  : minw,
                    'white-space':'nowrap',
//                    'max-width'  : maxw,
                    'height'     : height,
                     'overflow-y': 'auto'
                 });
            }else{
            	 this.selectbox.setStyles({
                     'min-width'  : minw,
                     'white-space':'nowrap',
//                     'max-width'  : maxw,
                     'max-height'     : height ,
                      'overflow-y': 'auto'
                  });
             this.box_div.setStyles({
            	 'white-space':'nowrap',
             	'min-width' : minw
//                 'max-width' : maxw
                 	});
            }
            this.toggle_selection();
            this.box.set('isbulid', 'true');
            this.currentElement = null;
        }
    },
    hide: function() {
        if(this.box.get('display') == 'true') {
            var fli = this.selectbox.getFirst('.swordselect-selected-none');
            var v = this.box.get('value');
            var rv = this.box.get('realvalue');
            var c = this.box.get('code');
            if($chk(v) && fli && this.currentElement == null) {
                if(this.box.get("handInput") == 'true') {
                    var n = this.selectbox.getFirst("div[value='" + rv + "']");
                    if(!$defined(n) || (n && n.get('caption') != v))this.box.set({'realvalue':v,'code':v});
                } else {
                 //   this.change_item(fli, true); 0528
                	this.box.set('value', "");
                    this.box.set('code', "");
                    this.box.set('realvalue', "");
                }
            } else if(!$chk(v) || !$chk(c) || !$chk(rv)) {
                if(this.box.get("handInput") == "true") {
                    this.box.set({'realvalue':v,'code':v});
                } else {
                    this.box.set('value', "");
                    this.box.set('code', "");
                    this.box.set('realvalue', "");
                }
                var child = this.options.child;
                while($defined(child)) {
                    var childSel = this.swordParent.getWidget(child).clearOptions();
                    child = childSel.options.child;
                }
            } else if(this.box.get("handInput") == "true" && this.currentElement == null) {
                var n = this.selectbox.getFirst("div[value='" + rv + "']");
                if(!$defined(n) || (n && n.get('caption') != v))
                    this.box.set({'realvalue':v,'code':v});
            }
            this.box_div.setStyles({'left':'-500px','top':'-500px'});
            //this.box_div.fade('out');
            this.box_div.set("state", "");
            this.selDiv.removeClass('swordselect-selimg-over');
            this.box.set('display', 'false');
            this.selectbox.getElements('div').each(function(li) {
                if(li.getProperty('index') == this.selectedIndex) {
                    this.unselect_lis();
                    this.currentElement = li.addClass('swordselect-selected');
                }
            }.bind(this));
            if(this.box.get('rule')) {
                this.validate.validate(this.box);
            }
            this.options.onHide = this.box.get("onHide");
            if($defined(this.options.onHide) && $chk(this.options.onHide)) {
                this.execGridOnFinished();//onchange时，更新表格数据
                this.getFunc(this.options.onHide)[0](this.currentElement, this);
            }
        }
    },
    show: function() {
        if(!$defined(this.box.get('display')) || this.box.get('display') == 'false') {
        	this.reBuild(this.box.retrieve("data"));
        	var widgetid = this.options.pNode.get("id");//判断是swordform还是grid
        	if($defined(widgetid)){
        			if(widgetid.indexOf("tpl")>=0)
        		     this.options.onShow = this.box.get("onShow");
        	}else{
	        	if(typeof(this.options.onShow)=="function"){
	        		this.options.onShow = null;
	        	}
        	}
            if($defined(this.options.onShow) && $chk(this.options.onShow)) {
                this.getFunc(this.options.onShow)[0](this,this.selectbox);
            }
            this.selDiv.addClass('swordselect-selimg-over');
            if(this.selectbox.getElements('div').length > 0) {
                this.box_div.setStyles({'display':'block'
                    //,'left':this.box._getPosition().x
                });
                xyposition(this.box, this.box_div);
                //this.box_div.fade('in');
                this.def_select(this.box.get('code'));
            }
            this.box.set('display', 'true');
        }
    },
    reBuild: function(data) {
    	if(this.selectbox){
            this.selectbox.getElements('div').each(function(li) {
                li.dispose();
            });
            this.box_div.set("id",this.box.get("id"));
        }else{
        	this.createBoxDiv();
        }
        this.options.data = data;
        var loadData = this.getOptionsData();
        if(!$defined(loadData)) {
            var pcode,tid = this.box.get("tid");
//            if(!$defined(tid) && !$chk(tid) && !$chk(this.box.retrieve("onSubmitBefore")))return;
//            if(!$defined(tid) && !$chk(tid) && !$chk(this.box.get("onSubmitBefore"))) {
//                if(this.exSelectDataFunc) {
//                    this.exSelectDataFunc();
//                    this.build_options(this.getOptionsData());
//                }
//            } else {
                if(this.isMulti() && $defined(this.box.get("parent"))) {
                    pcode = this.getParentValue();
                }
                this.getDataInCache(tid, this.box.get("dataname") || this.box.get("name"), pcode);
//            }
        } else {
            this.build_options(loadData);
        }
    },
    clearOptions:function(box, bz) {
        box.set('text', '');
        box.set({'value':'','code':'','realvalue':''});
        if(bz != false) {
            this.selectbox.getElements('div').each(function(li) {
                li.dispose();
            });
            box.set("isBuild", "false");
        }
        if(this.grid) {
            box.set({'caption':''});
            this.grid.updateCell(box, '');
        }
        return this;
    },
    toggle_selection: function() {
//        this.selectbox.getElements('div').each(function(li) {
//            li.addEvent('mouseenter', function() {
//                this.unselect_lis();
//                this.currentElement = li.addClass('swordselect-selected');
//                this.selectedIndex = this.currentElement.getProperty('index');
//                this.options.onSelect = this.box.retrieve("onSelect");
//                if($defined(this.options.onSelect) && $chk(this.options.onSelect)) {
//                    this.getFunc(this.options.onSelect)[0](this.currentElement);
//                }
//            }.bind(this));
//        }.bind(this));
    },
    unselect_lis: function() {
        this.selectbox.getChildren().removeClass('swordselect-selected');
    }

    ,getDataDivFxScroll:function() {
        if(this.dataDivFxScroll == null) {
            this.dataDivFxScroll = new Fx.Scroll(this.selectbox, {duration:10});
        }
        return this.dataDivFxScroll;
    },
    def_select:function(id) {
        var nodes = this.selectbox.getChildren();
        var i;
        for(i = 0; i < nodes.length; i++) {
            nodes[i].removeClass('swordselect-selected-fix');
            if(id == nodes[i].get('value')) {
                this.currentElement = nodes[i].addClass('swordselect-selected-fix');
                this.getDataDivFxScroll().toElement(nodes[i]);
                this.selectedIndex = this.currentElement.getProperty('index');
            }
        }
    },
    change_item:function(li, notHide) {
        if(li) {
            this.unselect_lis(this.selectbox);
            this.selectedIndex = li.getProperty('index');
            this.currentElement = li;
            this.currentElement.addClass('swordselect-selected');
        }
        if(!this.currentElement && !notHide) {
            this.hide();
            return;
        }
        var oCode = this.box.get('code');
        var excuteChange = true;
        var alldb = this.currentElement.retrieve("allDb");
        this.box.set('value', this.genarateInputContent(alldb));
        var nowCode = this.currentElement.get('value');
        this.box.set('code', nowCode);
        if(oCode == nowCode)excuteChange = false;
        this.box.store('allDb', alldb);
        this.box.set('realvalue', this.genarateContent(this.currentElement.retrieve("allDb")));
        this.getBoxParent().set({'code':this.currentElement.get('value'),'realvalue':this.genarateContent(this.currentElement.retrieve("allDb"))});
        if(excuteChange) {
        	this.clearChildData();
            /*var child = this.getBoxParent().get("child") || this.box.get("child");
            while($defined(child)) {
                var cSel = this.getBoxParent().retrieve("space").getElements("*[name='" + child + "']")[0];
                if($defined(cSel)) {
                    this.clearOptions(cSel);
                    child = cSel.get("child");
                } else
                    break;
            }*/
        }
        this.options.onChange = this.box.get("on_change");
        if(!notHide)this.hide();
        if($defined(this.options.onChange) && $chk(this.options.onChange) && excuteChange) {
            var opData = this.getOptionsData();//必须在更新表格数据前执行，否则报错
            this.execGridOnFinished();//onchange时，更新表格数据
            if($chk(opData)) {
                this.getFunc(this.options.onChange)[0](this.currentElement, opData[this.selectedIndex], this);
            } else {
                //延迟加载数据
                this.getFunc(this.options.onChange)[0](this.currentElement, this.currentElement.retrieve('allDb'), this);
            }
        }
        this.options.onSelect = this.box.get("onSelect");
        if($chk(this.options.onSelect)&&$chk(this.getFunc(this.options.onSelect)[0])) {
        	this.getFunc(this.options.onSelect)[0](li);
        }
    },
    getChildEls:function(name){
    	if(this.grid){
    		if(this.gridMulti){
    			return  this.gridSpace.getChildren("div[parent='"+name+"']");
    		}else{
    			return [];
    		}
    	}else{
    		return this.box.getParent().retrieve("space").getElements("input[parent='"+name+"']");
    	}
    	
    }
    ,clearChildData:function(){
    	var temp = this;
    	var childEls=this.getChildEls(this.box.get("name"));
        childEls.each(function(item,index){
        	var itemChilds = temp.getChildEls(item.get("name"));
        	itemChilds.each(function(itemC,index){
        		itemC.set("value", "");
        		itemC.set("realvalue", "");
        		itemC.set("code", "");
        		itemC.store("allDb", null);
        		item.set("caption","");
            	item.set("text","");
            	item.set("title","");
        	});
        	item.set("value", "");
        	item.set("realvalue", "");
        	item.set("code", "");
        	item.store("allDb", null);
        	item.set("caption","");
        	item.set("text","");
        	item.set("title","");
        });
    },
    change_item_on_keyup: function(e) {
        if(e.key == 'tab') return true;
        if(e.key == 'esc') {
            this.hide();
            return true;
        }
        if($chk(this.box.getAttribute("readonly"))) return;
        if(e.key == 'enter') {
            if(this.grid)var cell = this.box.getParent('div.sGrid_data_row_item_div');
            this.change_item();
            this.execGridOnFinished();
            if(this.grid)this.grid.nextCell(cell);
        }
        if(e.key == 'backspace' || e.key == 'delete') {
            if(this.box.get("readonly")) {
                e.stop();
                return;
            }
            if(this.box.get("mode") == 2) {
                this.box.set("code", "");
            } else {
                this.box.set("realvalue", "");
                this.box.set("code", "");
                this.box.store("allDb", null);
                try {
                	this.clearChildData();
                   /* var child = this.getBoxParent().get("child") || this.box.get("child");
                    while($defined(child)) {
                        var cSel = this.getBoxParent().retrieve("space").getElements("*[name='" + child + "']")[0];
                        if($defined(cSel)) {
                            this.clearOptions(cSel, false);
                            child = cSel.get("child");
                        } else
                            break;
                    }*/
                    this.options.onChange = this.box.get("on_change");
                    if($defined(this.options.onChange) && $chk(this.options.onChange) && ov != "") {
                        this.execGridOnFinished();
                        this.getFunc(this.options.onChange)[0](null, null, this);
                    }
                } catch(e) {
                }

            }
            this.selectbox.getChildren(".swordselect-selected-fix").removeClass("swordselect-selected-fix");
            this.selectbox.getChildren(".swordselect-selected").removeClass("swordselect-selected");
            this.currentElement = null;
            e.stop();
        }
        if((e.key == 'up' || e.key == 'down') && e.alt) {
            (this.box.get('display') == 'true') ? this.hide() : this.show();
            return true;
        }
        var li = null;
        if(e.key == 'up' || e.key == 'left') {
            li = this.change_element_by_method('getPrevious');
        } else if(e.key == 'down' || e.key == 'right') {
            li = this.change_element_by_method('getNext');
        } else if(e.code == 36 || e.code == 33) {
            li = this.change_element_by_method('getFirst', true);
        } else if(e.code == 35 || e.code == 34) {
            li = this.change_element_by_method('getLast', true);
        } else {
            li = this.change_element_by_char(e.key);
        }
        if(li != null) {
            this.unselect_lis(this.selectbox);
            this.selectedIndex = li.getProperty('index');
            this.currentElement = li;
            this.currentElement.addClass('swordselect-selected');
            this.getDataDivFxScroll().toElement(li);
            this.options.onSelect = this.box.get("onSelect");
            if($defined(this.options.onSelect) && $chk(this.options.onSelect)) {
                var sFunc=this.getFunc(this.options.onSelect);
                if(sFunc.length>0){sFunc[0](li);}
            }
        }
    }
    ,
    change_element_by_method: function(method, from_child) {
        if(!this.currentElement)return this.currentElement = this.selectbox.getFirst("div:not(.swordselect-selected-none)");
        return from_child ? this.currentElement.getParent()[method]("div:not(.swordselect-selected-none)") : this.currentElement[method]("div:not(.swordselect-selected-none)");
    },
    change_element_by_char: function(key) {
        var nv = this.box.get("value");
        var vName = this.box.get("name");
        if(this.box.get("mode") == 2) {
            this.selectLoading();
            var tid = this.box.get("tid");
            this.getNextPageData.bind(this)();
        } else {
            this.filterSelectBox(nv);
        }
    }
    ,
    filterSelectBox:function(v) {
        this.selectbox.getChildren().each(function(li) {
            if(li.get('value').search(v) == -1 && li.get('text').search(v) == -1){
                li.addClass("swordselect-selected-none");
            }else{
                li.removeClass("swordselect-selected-none");
            }
            if(li.get('value')==v){
            	li.addClass("swordselect-selected");
            }
        });
        this.currentElement = null;
    }
    ,
    getNextPageData:function(bz) {
        var vName = this.box.get("name");
        this.selectLoading();
        if($defined(bz)) {
            this.getSelectSoleData(this.sConsole.retrieve("curPage").toInt() + bz);
        } else {
            this.calculateConsole("clear");
            this.getSelectSoleData(1);
        }
    }
    ,
    getSelectSoleData:function(curPage) {
        var nv = this.box.get("value");
        var code = this.box.get("code");
        var tid = this.box.get("tid");
        var vName = this.box.get("name");
        if(!$chk(nv) || !$defined(nv)) {
            code = "";
        }
        try {
            var req = pc.getReq({'tid':tid,'widgets':[
                {
                    'sword':"SwordForm",
                    'name' :this.box.get("name"),
                    'data' :{
                        'caption':{value:nv},
                        'pcode':{value:code},
                        'targetPage':{'value':curPage},
                        'rowsOfPage':{'value':10}
                    }
                }
            ]});
            pc.postReq({
                'req':req,
                'loaddata':"widget",
                'onSuccess':function(res) {
                    this.unselectLoding();
                    if(this.box.get("name") != vName) {
//                        logger.debug("当前操作的select已经转移，不创select选择框！");
                    } else {
                        this.calculateConsole("init", null, res.getAttr("totalRows"));
                        this.build_options(res.data[0].data);
                    }
                }.bind(this),
                onError:function() {
                    alert("从服务器端获取数据出错了,请求的tid为【" + tid + "】");
                }.bind(this)
            }).delay(1000, this);
        } catch(e) {
            return;
        }
    }
    ,
    calculateConsole:function(cP, bz, rows) {
        if(cP == "init") {
            this.sConsole.store("rows", rows);
            this.sConsole.store("pages", ((rows % 10) == 0) ? rows / 10 : (rows / 10 + 1));
            var curPage = this.sConsole.retrieve("curPage");
            if(!$defined(curPage))this.sConsole.store("curPage", 1);
        } else if(cP == "clear") {
            this.sConsole.store("rows", null);
            this.sConsole.store("curPage", null);
            this.sConsole.store("rows", null);
            this.sConsole.getElements("div").removeClass("swordselect_csl_hidden");
            this.sConsole.setStyle('display', 'none');
        } else {
            var rows = this.sConsole.retrieve("rows");
            if(rows / 1 < 10) {
                this.sConsole.setStyle('display', 'none');
            }
            var cp = this.sConsole.retrieve("curPage") / 1 + bz;
            var pages = this.sConsole.retrieve("pages") / 1;
            if(cp == 1) {
                this.sConsole.getElement("div.swordselect_csl_pre").addClass("swordselect_csl_hidden");
            } else if(cp == pages) {
                this.sConsole.getElement("div.swordselect_csl_next").addClass("swordselect_csl_hidden");
            }
            if(pages > 1) {
                this.sConsole.setStyle("display", '');
            }
        }
    }
    ,
    clear:function() {
        this.hide();
        this.box.destroy();
        this.selDiv.destroy();
    }
    ,
    dm2mc:function(node, dm, space) {
    	dm = dm + "";
        if(dm == '' || dm == null || dm == undefined) {
            //dm为空值并且定义defIndex/defValue时
            if(node.get('defIndex') || node.get('defValue')) {
                var rv = this.initData(node.get('defValue'), node, node.get('defIndex'));
                return {"code":node.get("code"),"caption":node.get("value"),"realvalue":rv};
            }
            return '';
        }
        if(dm.indexOf("|") > -1 && dm.indexOf("code") > -1 && dm.indexOf("caption") > -1) {
            //var rv = this.initData(dm, node);
            this.box = $(node);
            var h = dm.toHash();
            var obj = {};
            h.each(function(v, k) {
                obj[k] = v;
            }, this);
            var rv = this.genarateContent(obj);
            dm = {"code":h.get("code"),"caption":h.get("caption"),"realvalue":rv};
        } else {
            this.box = $(node);
            this.box.store("data", this.box.getChildren(">div"));
            var rNode,realvalue,pcode;
            if($chk(node.get('parent')) && $chk(space)) {
                if($type(space)=="element"){
            		var parentEl = space.getElement('[name=' + node.get('parent') + '][code]');
                    if(parentEl)pcode = parentEl.get('code');
            	}else {
            		pcode=space;
            	}
            }
            var datas = this.getOptionsData(pcode);
            if(!datas)return '';
            var data;
            for(var i = 0; i < datas.length; i++) {
                data = datas[i];
                if($type(data) == 'element') {
                    data = {caption:data.get('caption'),code:data.get('code'),pcode:data.get('pcode')};
                }
                if($chk(pcode)) {//级联下拉校验 pcode
                    if(data.pcode == pcode && data.code == dm) {
                        realvalue = this.genarateContent(data);
                        rNode = this.genarateInputContent(data);
                        break;
                    }
                } else {//单下拉
                    if(data.code == dm) {
                        realvalue = this.genarateContent(data);
                        rNode = this.genarateInputContent(data);
                        break;
                    }
                }
            }
            if(rNode && realvalue)dm = {"code":dm,"caption":rNode,"realvalue":realvalue,"allDb":data};
        }
        return dm;
    }
    ,
    disable:function(inputEl) {
        if($defined(inputEl)) {
            inputEl.set('disabled', 'true').addClass('select_input_disable');
            var sel = this.getImgEl(inputEl);
            if(inputEl.cloneFlag) {
                sel.setStyle('display', '');
                sel.getNext().setStyle('display', 'none');
            } else {
                sel.clone().addClass('swordselect-selimg-disable').inject(sel, 'before');
                sel.setStyle('display', 'none');
                inputEl.cloneFlag = true;
            }
        }
    }
    ,
    enable:function(inputEl) {
        if($defined(inputEl) && inputEl.cloneFlag) {
            var sel = this.getImgEl(inputEl);
            inputEl.erase('disabled').removeClass('select_input_disable');
            sel.setStyle('display', 'none');
            sel.getNext().setStyle('display', '');
        }
    }
    ,initEvent:function() {
    	var f=function(e){
    		if ($defined(e)) {
                if (this.box == $(new Event(e).target)) {
                    this.rebuild = false;
                } else {
                	this.box = $(new Event(e).target);
                    this.selDiv = this.box.getParent("td").getNext().getElement(".swordselect-selimg");
                    if (this.box.get("display") == 'true') {
                        this.hide();
                    }
                    this.rebuild = true;
                }
            }
        	if(!this.grid)this.options.pNode=$$("div[name="+this.box.get("name")+"]")[0];
            if (this.box.get('display') == 'true') {
                this.hide();
            } else {
                this.show();
                this.box.focus();
            }
    	}.bind(this);
    	this.box.addEvent('focus', function(e) {
//          this.execGridOnFinished();
			f(e);
		}.bind(this));
        this.box.addEvent('blur', function(e) {
        	this.setBoxValueFblur();
        	if (this.box.get('display') == 'true') {
                this.hide.delay(300,this);
            }
		}.bind(this));
        this.selDiv.addEvent('click', function(e) {
//                    this.execGridOnFinished();
        	if (this.selDiv == $(new Event(e).target)) {
                this.rebuild = false;
            } else {
                if (this.box.get("display") == 'true') {
                    this.hide();
                }
                this.selDiv = $(new Event(e).target);
                this.box = this.selDiv.getParent("td").getPrevious().getElement(".swordform_item_oprate");
                this.rebuild = true;
            }
            if(!this.grid)this.options.pNode=$$("div[name="+this.box.get("name")+"]")[0];
            if (this.box.get('display') == 'true') {
                this.hide();
            } else {
                //this.show();修改成focus的触发方式了.
                this.box.focus();
            }
        }.bind(this));
        this.box.addEvent("keyup", this.change_item_on_keyup.bind(this));
    }
    ,getCurData:function(){
    	return this.box.retrieve("allDb");
    }
    ,setBoxValueFblur:function(){
    	var hIStr=this.box.get('handInput'),
    	iVStr=this.box.get("value"),
    	realValue=this.box.get("realvalue");
    	var optDatas = this.getOptionsData();
    	var itemData=null;
    	if($chk(optDatas)){
    		var itemDatas=optDatas.filter(function(item){
        		if($type(item)=="element"){
        			return item.get("code")==realValue;
        		}
        		return item.code==realValue;
        	});
        	itemData = itemDatas.length!=0?itemDatas[0]:null;
    	}
    	if($chk(realValue)){
    		if(hIStr=="true"){//允许自定义录入
    			var caption=itemData.caption||itemData.get("caption");
    			if($chk(itemData)){
    				if(caption!=iVStr){
    					this.box.set("realvalue",iVStr);
    				}
    			}else{
    				this.box.set("realvalue",iVStr);
    			}
    		}else{
    			if(!$chk(itemData)){
	    			this.box.set("realvalue","");
	    			this.box.set("value","");
	    			this.box.set("code","");
    			}
    		}
    	}else{
    		if(hIStr=="true"){
    			this.box.set("realvalue",iVStr);
    		}else{
	    		this.box.set("value","");
	    		this.box.set("code","");
    		}
    	}
    }
});